<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入商品名称" v-model="queryInfo.query" @clear="getGoodsList" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddGoods">添加商品</el-button>
        </el-col>
      </el-row>

      <el-table :data="goodsData.list" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="封面" min-width="50px">
          <template slot-scope="scope">
            <img src="../../assets/logo.png" width="100%" v-real-img="realImg(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="商品ID" min-width="80px" prop="id"></el-table-column>
        <el-table-column label="商品名称" min-width="300px" prop="name"></el-table-column>
        <el-table-column label="副标题" min-width="300px" prop="subtitle"></el-table-column>
        <el-table-column label="价格" min-width="80px" prop="price"></el-table-column>
        <el-table-column label="状态" min-width="80px">
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 1 ? 'success' : 'danger'"
            >{{scope.row.status === 1 ? '上线' : '下架'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editGoods(scope.row.id)"
            >编辑</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteGoods(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="goodsData.total"
      ></el-pagination>
    </el-card>
    <el-dialog
      title="编辑商品"
      @close="editGoodsDialogClosed"
      :visible.sync="editGoodsDialogVisible"
      width="800px"
      center
    >
      <el-form
        ref="editGoodsFormRef"
        :model="editGoodsSubmitInfo"
        :rules="editGoodsSubmitRules"
        label-width="100px"
        size="medium"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editGoodsSubmitInfo.name" :placeholder="'原：'+editGoodsInfo.name"></el-input>
        </el-form-item>
        <el-form-item label="副标题" prop="subtitle">
          <el-input
            v-model="editGoodsSubmitInfo.subtitle"
            :placeholder="'原：'+editGoodsInfo.subtitle"
          ></el-input>
        </el-form-item>
        <el-form-item label="商品状态" prop="status">
          <el-radio-group v-model="editGoodsSubmitInfo.status" style="margin-left:20px;">
            <el-radio :label="1">
              <el-tag type="primary">上线</el-tag>
            </el-radio>
            <el-radio :label="0">
              <el-tag type="warning">下架</el-tag>
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属分类" prop="parentCategoryId">
          <el-cascader
            placeholder="默认为原所属分类"
            :options="categoryList"
            :props="categoryProp"
            v-model="selectKeys"
            @change="handleChange"
            clearable
            filterable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number v-model="editGoodsSubmitInfo.price" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number v-model="editGoodsSubmitInfo.stock" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="商品图片" prop="subImages">
          <el-upload
            :headers="uploadHeaders"
            action="http://localhost:8888/manage/product/upload"
            list-type="picture-card"
            :on-preview="editPreview"
            :on-success="editSuccess"
            :file-list="filelist"
            :on-remove="editRemove"
            :limit="4"
            multiple
            :on-exceed="editExceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" append-to-body>
            <img width="100%" :src="dialogImageUrl" alt />
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品描述" prop="detail">
          <quill-editor
            v-model="editGoodsSubmitInfo.detail"
            ref="quillEditorRef"
            :options="editorOption"
            @change="onQuillChange($event)"
            @ready="onQuillReady($event)"
          ></quill-editor>
          <el-upload
            class="quill-upload"
            action="http://localhost:8888/manage/product/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            ref="quillUpload"
            accept="image/*"
            multiple
            :on-success="quillSuccess"
          ></el-upload>
        </el-form-item>
        <el-button type="primary" style="margin-left:350px" @click="submitEdit">点击更新</el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
// 富文本编辑器工具栏配置
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // toggled buttons
  ['blockquote', 'code-block'],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: 'ordered' }, { list: 'bullet' }],
  [{ script: 'sub' }, { script: 'super' }], // superscript/subscript
  [{ indent: '-1' }, { indent: '+1' }], // outdent/indent
  [{ direction: 'rtl' }], // text direction

  [{ size: ['small', false, 'large', 'huge'] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ['link', 'image', 'video'],
  ['clean'] // remove formatting button
]
export default {
  data() {
    return {
      queryInfo: {
        query: null,
        pageNum: 1,
        pageSize: 5
      },
      uploadHeaders: {
        Authorization: sessionStorage.getItem('CURRENT_TOKEN')
      },
      // 指定页商品数据列表
      goodsData: {},
      //
      editGoodsDialogVisible: false,
      // 要编辑的商品信息
      editGoodsInfo: {},
      // 提交时的商品新信息
      editGoodsSubmitInfo: {
        id: 0,
        name: '',
        subtitle: '',
        parentCategoryId: 0,
        price: 0,
        stock: 0,
        subImages: '',
        detail: '',
        status: 0
      },
      // 级联选择器 数据源
      categoryList: [],
      // 分类选中数据
      selectKeys: [],
      //
      categoryProp: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      //
      dialogVisible: false,
      //
      dialogImageUrl: '',
      filelist: [],
      // 富文本编辑器配置
      editorOption: {
        placeholder: '',
        theme: 'snow', // or 'bubble'
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function(value) {
                if (value) {
                  // 触发input框选择图片文件
                  document.querySelector('.quill-upload input').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          }
        }
      },
      //
      editGoodsSubmitRules: {
        name: [
          {
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                this.editGoodsSubmitInfo.name = this.editGoodsInfo.name
                callback()
              }
              this.editGoodsSubmitInfo.name = this.editGoodsSubmitInfo.name.trim()
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        subtitle: [
          {
            validator: (rule, value, callback) => {
              if (value.trim() === '') {
                this.editGoodsSubmitInfo.subtitle = this.editGoodsInfo.subtitle
                callback()
              }
              this.editGoodsSubmitInfo.subtitle = this.editGoodsSubmitInfo.subtitle.trim()
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        status: [
          {
            validator: (rule, value, callback) => {
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        parentCategoryId: [
          {
            validator: (rule, value, callback) => {
              if (this.selectKeys.length === 0) {
                this.editGoodsSubmitInfo.categoryId = this.editGoodsInfo.parentCategoryId
              }
              if (this.selectKeys[this.selectKeys.length - 1] === this.editGoodsSubmitInfo.id) {
                callback(new Error('不能将父级设置在自身分类下，请重新选择！'))
              }
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        subImages: [
          {
            validator: (rule, value, callback) => {
              const imgs = []
              this.filelist.forEach(value => {
                if (value.response === undefined) {
                  imgs.push(value.name)
                } else {
                  imgs.push(value.response.data[0].uri)
                }
              })
              this.editGoodsSubmitInfo.subImages = imgs.join(',')
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        detail: [
          {
            validator: (rule, value, callback) => {
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        price: [
          {
            validator: (rule, value, callback) => {
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ],
        stock: [
          {
            validator: (rule, value, callback) => {
              callback()
            },
            required: true,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getGoodsList()
  },
  methods: {
    // 获取指定页的所有商品数据
    async getGoodsList() {
      const { data: res } = await this.$axios.get('manage/product/get_goods_list', {
        params: this.queryInfo
      })
      if (res.status !== 0) return this.$message.error(res.msg)
      this.goodsData = res.data
    },
    //
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getGoodsList()
    },
    //
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage
      this.getGoodsList()
    },
    //
    deleteGoods(id) {
      this.$confirm('操作会永久删除该商品，是否继续？', '删除提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$message.success('执行删除操作！')
          const { data: res } = await this.$axios.delete('manage/product/delete_goods/' + id)
          if (res.status !== 0) return this.$message.error(res.msg)
          this.$message.success(res.msg)
          // 刷新列表
          this.getGoodsList()
        })
        .catch(() => {
          this.$message.info('已取消删除操作！')
        })
    },
    // 编辑商品
    async editGoods(id) {
      const { data: res1 } = await this.$axios.get('manage/product/get_goods_detail/' + id)
      if (res1.status !== 0) return this.$message.error(res1.msg)
      this.editGoodsDialogVisible = true
      this.editGoodsInfo = res1.data
      this.editGoodsSubmitInfo.id = res1.data.id
      this.editGoodsSubmitInfo.name = res1.data.name
      this.editGoodsSubmitInfo.subtitle = res1.data.subtitle
      this.editGoodsSubmitInfo.categoryId = res1.data.parentCategoryId
      this.editGoodsSubmitInfo.price = res1.data.price
      this.editGoodsSubmitInfo.stock = res1.data.stock
      this.editGoodsSubmitInfo.subImages = res1.data.subImages
      this.editGoodsSubmitInfo.detail = res1.data.detail
      this.editGoodsSubmitInfo.status = res1.data.status
      // 获取分类数据
      const { data: res } = await this.$axios.get('manage/category/get_category_all')
      if (res.status !== 0) return this.$message.error(res.msg)
      this.categoryList = res.data
      // 处理filelist
      res1.data.subImages.split(',').forEach(value => {
        if (value === '') return
        const img = {
          name: value,
          url: res1.data.imageHost + value
        }
        this.filelist.push(img)
      })
    },
    // 跳转到添加商品界面
    goAddGoods() {
      this.$router.push('/goods_add')
    },
    //
    handleChange() {
      if (this.selectKeys.length === 0) {
        this.editGoodsSubmitInfo.categoryId = this.editGoodsInfo.parentCategoryId
        return
      }
      this.editGoodsSubmitInfo.categoryId = this.selectKeys[this.selectKeys.length - 1]
    },
    //
    editPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    //
    editSuccess(res, file, filelist) {
      console.log('编辑图片：上传success')
      this.filelist = filelist
    },
    //
    editRemove(file, filelist) {
      console.log('编辑图片：删除remove')
      this.filelist = filelist
    },
    //
    editExceed() {
      this.$message.warning('只能容纳最多四张图片!')
    },
    //
    editGoodsDialogClosed() {
      this.editGoodsInfo = {}
      this.$refs.editGoodsFormRef.resetFields()
      this.filelist = []
      this.selectKeys = []
      this.categoryList = []
    },
    // 富文本编辑器内容发生改变时立刻触发
    onQuillChange(value) {
      console.log('富文本编辑器内容改变：onQuillChange')
      this.editGoodsSubmitInfo.detail = value.html
    },
    // 富文本编辑器准备好时触发
    onQuillReady(value) {
      console.log('富文本编辑器准备完毕：onQuillReady')
    },
    //
    quillSuccess(response, file, filelist) {
      // file包含原文件信息以及服务器返回的数据
      // 获取富文本组件实例
      const quill = this.$refs.quillEditorRef.quill
      // 如果上传时出现错误
      if (response.status !== 0) return this.$message.error(response.msg)
      // 上传成功
      // 1.获取富文本中光标所在位置
      const index = quill.getSelection().index
      // 2.插入图片
      quill.insertEmbed(index, 'image', response.data[0].url)
      // 3.调整光标位置
      quill.setSelection(index + 1)
    },
    //
    submitEdit() {
      this.$refs.editGoodsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$axios.post('manage/product/insert_goods', this.editGoodsSubmitInfo)
        if (res.status !== 0) return this.$message.error(res.msg)
        this.$message.success(res.msg)
        this.editGoodsDialogVisible = false
        this.getGoodsList()
      })
    },
    //
    realImg(row) {
      if (row.mainImage === null) {
        return 'false'
      }
      return row.imageHost + row.mainImage
    }
  }
}
</script>

<style lang="less" scoped>
</style>
